package com.it.tydic.estate.common.security;

import com.it.tydic.estate.module.model.inner.TbResource;
import com.it.tydic.estate.module.model.inner.TbRole;
import com.it.tydic.estate.module.service.ResourceService;
import com.it.tydic.estate.module.service.RoleService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import tk.mybatis.mapper.util.StringUtil;

import javax.annotation.PostConstruct;
import java.util.*;

@Configuration
@EnableWebSecurity
public class MyInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    private static Map<String, Collection<ConfigAttribute>> resourceMap = null;
    private org.slf4j.Logger LOG = LoggerFactory.getLogger(getClass());

    @Autowired
    private ResourceService powerService;

    @Autowired
    private RoleService roleService;

    /**
     * 加载资源，初始化资源变量
     */
    @PostConstruct
    public void loadResourceDefine() {
    	long startTime = System.currentTimeMillis();
        if (resourceMap == null) {
            resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
            List<TbRole> roles=roleService.findRoleList();
            if(roles.size() >= 0) {
            	for (TbRole role : roles) {
            		  ConfigAttribute attribute = new SecurityConfig(role.getRoleId());
            		  List<TbResource> resources = powerService.findResourceListByRoleId(role.getRoleId());
            		  for (TbResource power : resources) {
            			  if(StringUtil.isNotEmpty(power.getResourceUrl())) {
                              if(resourceMap.containsKey(power.getResourceUrl())) {
                            	  Collection<ConfigAttribute> configAttributes=resourceMap.get(power.getResourceUrl());
                            	  configAttributes.add(attribute);
                              }else {
                            	  Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();
                                  configAttributes.add(attribute);
                            	  resourceMap.put(power.getResourceUrl(), configAttributes);
                              }

            			  }
                      }
				}
            }
          
        }
        System.out.println("============================================");
		System.out.println(resourceMap.toString());
		System.out.println(resourceMap.size());
		long endTime = System.currentTimeMillis();
		LOG.info("初始化资源URL和角色对应关系耗时"+(endTime-startTime)/1000.0+"秒,包含记录"+resourceMap.size()+"条");
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        if (resourceMap == null) loadResourceDefine();
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
       // 返回当前 url  所需要的权限
         return resourceMap.get(requestUrl);
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }



}
